<template>
    <div style="margin-left: 20px;">
        <div class="picker" style="margin-top: 20px;">


            <div >
                <el-date-picker
            
            v-model="value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            >
            
          </el-date-picker>
            </div>
           
   <div class="right_btn">
    <!-- <el-button :type="type[0]" @click="toggleType(0)"   size="small" >新增客户数</el-button>
    <el-button :type="type[1]" @click="toggleType(1)"  size="small" >学科客户分布</el-button> -->
    <ul>
      <li  :class="{ active: activeIndex === 0 }" @click="handleMenuClick(0)"><a href="#" style="text-decoration: none;color: inherit; ">新增客户数</a></li>
      <li :class="{ active: activeIndex === 1 }" @click="handleMenuClick(1)"><a href="#" style="text-decoration: none;color: inherit; ">学科客户分布</a></li>
    </ul>

   </div>
        </div>
<div class="line_chart">
<div id="container1"  v-show="activeIndex === 0" >
</div>
<div id="container2" v-show="activeIndex === 1" >
</div>

</div>
</div>
<div  class="tabname_two"><h1>客户统计报表</h1>
<!-- <button class="btn">导出</button> -->
</div>
<!-- //==============================================导出以下table表格 -->
<div class="box2">
  <div class="inp">
  <el-form 
   :inline="true"
   :model="formInline" 
  label-position="top"
  style="display: flex; align-items: center;
 justify-content: space-between;
 background-image: linear-gradient(to left, rgba(205, 205, 205, 0.109), transparent), linear-gradient(to right, rgba(205, 205, 205, 0.089), transparent);
 border-radius: 40px;
"
  >
    <el-form-item label="渠道来源">
      <el-select v-model="formInline.sourceChannel" clearable  placeholder="请选择" style="width: 100%">
        <el-option
      v-for="item in options"
      :key="item.sourceChannel"
      :label="item.sourceChannel"
      :value="item.sourceChannel"
    />
      </el-select>
    </el-form-item>
    <el-form-item label="归属部门">
    <el-select v-model="formInline.departmentAffiliation" clearable placeholder="请选择归属部门" style="width: 100%">
      <el-option
      v-for="item in options"
      :key="item.departmentAffiliation"
      :label="item.departmentAffiliation"
      :value="item.departmentAffiliation"
    />
    </el-select>

  </el-form-item>
    <el-form-item label="归属人">
    <el-input v-model="formInline.belonger" placeholder="请输入归属人" style="width: 100%"></el-input>
  </el-form-item>
<el-form-item  label="&nbsp"  >
  <el-button type="primary" round  @click="onSubmit">搜索</el-button>
  <el-button type="info" round  @click="btnResetform">重置</el-button>
</el-form-item>


  </el-form>
</div>
 
<!-- ===================================================table -->
<el-table :data="customerTable" stripe>
  <el-table-column
      type="selection"
      width="55">
    </el-table-column>
  <el-table-column
      prop="id"
      label="客户ID"
   >
    </el-table-column>
  <el-table-column
      prop="clientName"
      label="姓名"
   >
    </el-table-column>
  <el-table-column
      prop="courseSubject"
      label="课程资料"
      align="center"
   >
    </el-table-column>
  <el-table-column
      prop="courseName"
      label="课程名称"
      align="center"
   >
    </el-table-column>
  <el-table-column
      prop="sourceChannel"
      label="渠道来源"
      align="center"
   >
    </el-table-column>
  <el-table-column
      prop="belonger"
      label="归属人"
      align="center"
   >
    </el-table-column>
    
  <el-table-column
      prop="creationTime"
      label="成交时间"
      align="center"
      width="180px"
      sortable
   >
    <template #default="{ row }">
          {{ formatTimestamp(row.creationTime) }}
        </template>
    </el-table-column>
  <el-table-column
      label="操作"
      align="center"
   >
   <el-button  type="text" >详情</el-button>
    </el-table-column>
   
</el-table>
<div class="block" >
<!-- //            ====分页======= -->
<el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="queryParams.total">
    </el-pagination>
  </div>

</div>

       

</template>

<script setup>//=====================================================script===========================

// import Piecontainer_two from './Piecontainer_two.js'
import {ref,onMounted, } from "vue";
import dayjs from "dayjs";
import { Line,Pie } from '@antv/g2plot';//导入饼图
const data2=ref('')
// const datapie=ref('')
// const datapie2=ref()
// console.log(data3.value);
const getline=ref({
  accountSize:'',
  dateList:'',
  userNew:'',
})  
const value1=ref('')
const activeIndex=ref(0)
const customerTable=ref([])//渲染table的数据
const formInline=ref({
  belonger:'',//归属人
  departmentAffiliation:"",//所属部门
  sourceChannel:''//所属渠道
})
// const total=ref('')
const queryParams=ref({
  page: "1",
  pageSize: "2",
  total:'',
  // belonger: "园园",
  // departmenTaffiliation: "学习部门",
  // sourceChannel: "线上活动"
})
const options =ref([ {
    value: '线上活动id',
    label: 'sourceChannel线上活动id',
  },
  {
    value: '学习部门id',
    label: 'departmentAffiliation学习部门id',
  },
  ])
import { getGenTable,getUserChart,getdisciplineChart } from "@/api/count.js";

// 新增用户图表  
const getUserChartAPI=async()=>{
  getline.value =  await getUserChart({
            "startTime": "2023-06-09",
             "endTime": "2023-06-14"
           })

// console.log('折现图',getline.value)
}
// 学科客户分布图表    
const getdisciplineChartAPI=async()=>{
   const data22  =  await getdisciplineChart({
            "startTime": "2023-06-09",
            "endTime": "2023-06-16"
           })
console.log('学科',data22);
data2.value=data22.data
console.log('需要给图的数据',data2.value);
          //  const newData = data22
  // .reduce((acc, curr) => acc.concat(curr), []) // 将所有数组连接成一个数组
  // .map(item => ({_rawValue: item})); // 将每个元素转换成包含 _rawValue 属性的新对象

    // data22.forEach(item=>{
    //   data2.value.push({subjects:item.name,value:+item.value})
    // })
           
          //  console.log('饼图数据',newData);
//            data2.value = newData.map((subjectScores, index) => {
//   const sum = subjectScores.reduce((acc, curr) => acc + curr.score, 0);
//   const average = sum / subjectScores.length;
//   const subjectName = newData.name[index];
//   return {subjects: subjectName, value: average};
// });
//            console.log(data2.value);
//            datapie.value = JSON.stringify(data2.value);

// console.log(datapie.value);
}

// const showContainer=ref(true)//控制饼图开关
const seriesKey = 'series';
const valueKey = 'value';
function processData(data, yFields, meta) {
  const result = [];
  data.forEach((d) => {
    yFields.forEach((yField) => {
      const name = meta?.[yField]?.alias || yField;
      result.push({ ...d, date: d.date, [seriesKey]: name, [valueKey]: d[yField] });
    });
  });
  return result;
}

// ================================  折线数据+Pie
// getline.value
//   //饼图数据
  const renderPieChart=()=>{
    const data=
    [
{ "subjects": "前端", "value": 33.33 },
{ "subjects": "人工智能", "value": 0.0 },
{ "subjects": "Python", "value": 0.0 },
{ "subjects": "大数据", "value": 0.0 },
{ "subjects": "测试", "value": 0.0 },
{ "subjects": "UI", "value": 33.33 },
{ "subjects": "Java", "value": 33.33 },
{ "subjects": "新媒体", "value": 0.0 },
{ "subjects": "产品经理", "value": 0.0 }
]
// console.log('标杆',data);

    const container = document.getElementById('container2');

    const piePlot = new Pie(container, {
  appendPadding: 10,
  data,
  
  angleField: 'value',
  colorField: 'subjects',
  radius: 0.7,
 
  legend:{
    position: 'bottom', // 自定义位置
  },
  innerRadius: 0.6,
  tooltip: {
      enterable: true,
      formatter: (datum) => {
        // 在Tooltip提示消息内容后面添加百分号
        return {
          name: datum.subjects,
          value: datum.value + '%',
        };
      },
    },
  label: {
    type: 'inner',
    offset: '-50%',
    content: '',
    
    style: {
      textAlign: 'center',
      fontSize: 14,
    },
  },
  interactions: [{ type: 'element-selected' }, { type: 'element-active' }],
  statistic: {
    title: false,
    content: {
      style: {
        whiteSpace: 'pre-wrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
      },
      content: '成交客户2700个',
    },
  },
});

  piePlot.render();
  }


const handleMenuClick=(index)=>{
  // console.log(index);
  activeIndex.value=index



}
//折线
const renderLineChart=()=>{
  fetch('https://gw.alipayobjects.com/os/antfincdn/nHVKXA8ClI/multiple-measures-line-data.json')
    .then((data) => data.json())
    .then((data) => {
     
      const meta = {
        date: {
          alias: '销售日期',
        },
        price: {
          alias: '新增客户数量（个）',
        },
        discount_price: {
          alias: '客户总数量（万个）',
        },
      };
      // const containerSelector = showContainer.value ? '#container' : '#container1'; // 根据showContainer的值选择容器元素选择器
      const container = document.getElementById('container1');
      const line = new Line(container, {
        data: processData(data, ['price', 'discount_price'], meta),
        padding: 'auto',
        xField: 'date',
        yField: valueKey, // 使用数组传递多个yField
        seriesField: seriesKey,
        appendPadding: [0, 8, 0, 0],
        smooth: true, // 添加 smooth 属性以显示平滑曲线
        legend:{
    position: 'bottom', // 自定义位置
  },
  color: ['#18c490', '#f8725f'], // 设置曲线的颜色为绿色和橘色
        // colorMap:{
        //   '新增客户数量（个）':'#c03737',
        //   '客户总数量（万个）':'#ff7f50',
        // },
        // yAxis: [
        //   {
        //     showTitle: true,
        //     title: '新增客户数量（个）',
        //   },
        //   {
        //     showTitle: true,
        //     title: '客户总数量（万个）',
        //     position: 'right', // 将第二条折线的yField显示在右侧
            
        //   },
        // ],
      });

      line.render();
    });
}
//                                            table获取搜索数据
const getGenTableAPI=async()=>{
const {data,size,currentPage}= await getGenTable(queryParams.value)
// console.log(res);
customerTable.value=data
options.value=data
queryParams.value.page=currentPage
queryParams.value.pageSize=size
queryParams.value.total=data.length


}
const formatTimestamp = (timestamp) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss');
};
///重置按钮
const btnResetform=()=>{
  formInline.value={
  belonger:'',//归属人
  departmentAffiliation:"",//所属部门
  sourceChannel:''//所属渠道
  
}
getGenTableAPI()
// getGenTable()
}
//搜索按钮
const onSubmit = async()=>{
  console.log('搜索框里面内容',formInline.value);
const {data,size,total,}= await getGenTable(
{...queryParams.value,...formInline.value}
  )
  console.log(data,size,total);
  customerTable.value=data
  queryParams.value.pageSize=size
queryParams.value.total=total


}
onMounted(()=>{
  getGenTableAPI()//table获取搜索数据
  renderPieChart()//饼图
  renderLineChart()//折线
  getUserChartAPI()//获取折现用户数据
  getdisciplineChartAPI()//获取饼图用户数据
 
})

</script>
<style scoped lang="less">
.picker{
    display: flex;
    justify-content: space-between;
    .right_btn{
       width: 220px
       ;
       height: 40px;
       display: flex;
       justify-content: space-evenly;
        // margin-left: 70%;
        margin-right: 20px;
        border-radius: 5px;
        padding: 4px;
        border: 1px solid rgba(171, 168, 168, 0.052);
        background-color: #cdcdcd28;
        button{
          border: 1 solid red;
        }
        ul{
list-style-type: none;
display: flex;
padding-left: 0px;
margin-left: 2px;
li{
  margin-top: -4px;
  color: #aeb5c4;
  font-size: 14px;
  height: 32px;
  border-radius: 6px;
  padding: 0px 7px;
  font-family: PingFangSC,PingFangSC-Semibold;
  font-weight: 600;
  display: flex;
  width: 95px;
  align-items: center;
  justify-content: center;
  text-align: center;
  transition: all 0.2s ease-in-out;
}
        }
        .active{
          color: #05cc95;
          transition: all 0.5s ease-in-out;
          background-color: rgb(255, 255, 255);
          box-shadow: 0 6px 1px 0 rgba(0,0,0,.06);

        }
    }
}
.line_chart{
    margin-top: 20px;
    background-color: rgba(135, 207, 235, 0);
    width: 100%;
    height: 430px;
// #container2{
//   // width: 100%;
//   //   height: 430px;
//     // background-color: #78a721;
// }
}
.tabname_two{
      height: 80px;
      background-color: rgb(255, 255, 255);
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .btn{
        background-color: rgb(253, 112, 100);
        border-radius: 40px;
        border: none;
        height: 40px;
        width: 100px;
        color: #ffffff;
        font-size: 17px;
        margin-right: 40px;
      }
    }
    .inp{
    background-color: #ffffff;
     margin-bottom: 10px;
      padding: 25px 56px 14px 17px;
  h3,h5{
   
    font-weight: 300;
  }
    }
    .block{
      display: flex;
      justify-content: center;
      padding: 2px 5px;
      margin-top:24px;
    }
    #container_two{
      width: 100%;
      height: 350px;
    }
    #container{
      width: 100%;
      height: 350px;
    }
</style>